package com.authine.cloudpivot.ext.utils.system;

import com.alibaba.cola.exception.Exceptions;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @ClassName BeanUtils
 * @Description: bean工具类
 * @Author fj
 * @Date 2021/9/16
 * @Version V1.0
 **/
@Slf4j
public class BeanUtils {
    /**
     * 将javaBean转成bo需要的map
     * @param obj   javaBean
     * @return      map
     */
    public static Map<String, Object> bean2Map(Object obj) {
        if (obj == null) {
            Exceptions.throwBizException(ErrorCodeEnum.BIZ_PARAMS_ERR);
        }
        Map<String, Object> map = Maps.newHashMap();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!"class".equals(key)) {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            log.info("transBean2Map Error " + e);
            Exceptions.throwBizException(ErrorCodeEnum.BIZ_PARAMS_ERR);
        }
        return map;
    }
}
